Page({
  data: {
    complaintTypes: [
      { value: 'service', name: '服务质量' },
      { value: 'behavior', name: '技师行为' },
      { value: 'payment', name: '支付问题' },
      { value: 'other', name: '其他问题' }
    ],
    formData: {
      technician: '',
      order: '',
      complaint_type: 'service',
      title: '',
      content: '',
      evidence_images: []
    },
    technicians: [],
    orders: [],
    showTechnicianPicker: false,
    showOrderPicker: false,
    technicianIndex: 0,
    orderIndex: 0
  },

  onLoad: function(options) {
    this.loadTechnicians();
    this.loadOrders();
  },

  loadTechnicians: function() {
    const app = getApp();
    app.request({
      url: '/user/technicians/',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            technicians: res.data
          });
        }
      }
    });
  },

  loadOrders: function() {
    const app = getApp();
    app.request({
      url: '/orders/',
      method: 'GET',
      success: (res) => {
        if (res.statusCode === 200) {
          // 只显示已完成的订单
          const completedOrders = res.data.filter(order => order.status === 'completed');
          this.setData({
            orders: completedOrders
          });
        }
      }
    });
  },

  bindTechnicianChange: function(e) {
    const index = e.detail.value;
    this.setData({
      'formData.technician': this.data.technicians[index].id,
      technicianIndex: index
    });
  },

  bindOrderChange: function(e) {
    const index = e.detail.value;
    this.setData({
      'formData.order': this.data.orders[index].id,
      orderIndex: index
    });
  },

  bindTypeChange: function(e) {
    this.setData({
      'formData.complaint_type': e.detail.value
    });
  },

  onTitleInput: function(e) {
    this.setData({
      'formData.title': e.detail.value
    });
  },

  onContentInput: function(e) {
    this.setData({
      'formData.content': e.detail.value
    });
  },

  chooseImage: function() {
    const that = this;
    wx.chooseMedia({
      count: 3 - this.data.formData.evidence_images.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFiles = res.tempFiles;
        const imageUrls = [];
        
        // 上传图片到服务器
        const uploadPromises = tempFiles.map(file => {
          return new Promise((resolve, reject) => {
            const app = getApp();
            wx.uploadFile({
              url: `${app.globalData.baseUrl}/complaints/upload_evidence/`,
              filePath: file.tempFilePath,
              name: 'image',
              header: {
                'Authorization': `Bearer ${app.globalData.token}`
              },
              success: (uploadRes) => {
                if (uploadRes.statusCode === 201) {
                  const data = JSON.parse(uploadRes.data);
                  resolve(data.url);
                } else {
                  reject(new Error('上传失败'));
                }
              },
              fail: (err) => {
                reject(err);
              }
            });
          });
        });
        
        // 等待所有图片上传完成
        Promise.all(uploadPromises)
          .then(urls => {
            that.setData({
              'formData.evidence_images': [...that.data.formData.evidence_images, ...urls]
            });
          })
          .catch(err => {
            wx.showToast({
              title: '图片上传失败',
              icon: 'none'
            });
          });
      }
    });
  },

  removeImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.formData.evidence_images;
    images.splice(index, 1);
    this.setData({
      'formData.evidence_images': images
    });
  },

  submitComplaint: function() {
    // 表单验证
    if (!this.data.formData.title) {
      wx.showToast({
        title: '请输入投诉标题',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.formData.content) {
      wx.showToast({
        title: '请输入投诉内容',
        icon: 'none'
      });
      return;
    }
    
    const app = getApp();
    app.request({
      url: '/complaints/create/',
      method: 'POST',
      data: this.data.formData,
      success: (res) => {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '投诉提交成功',
            icon: 'success'
          });
          
          // 返回投诉列表页面
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: '提交失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  }
});